<?php
namespace Home\Controller;

use Utuo\ForegroundController;

class DriverController extends ForegroundController {
	
	private $termId = null;
		
	private $rank = null; // 实时排行
	
	private $rankSnap = null; // 历史发布
	
	private $rankConfig = array(
		'noRandText' => '无排名', // 无名次显示
	);
	
	private $driverTerm = null;
	
	public function _init() {
		if( false and (!$this->checkMicroMessenger() or !$this->open_id) ) {
			if ( IS_AJAX ) {
				$this->ajaxError("请从微信中进入.");
			} else {
				header("Content-Type:text/html;charset=utf-8");
				exit('请从微信中进入');
			}
		}
		layout(false);
		$this->setModelName("Site");
		if ( NOW_TIME >= strtotime("2015-1-1") ) {
			$this->termId = 4;
		} else {
			$this->termId = 3;
		}
		$driverTerm = M("DriverTerm")->where("id=%d and cid=%d", $this->termId, $this->cid)->find();
		if( !$driverTerm ) {
			$driverTerm = M("DriverTerm")->where("cid=%d and status=1", $this->cid)->order('id desc')->find();
			$this->termId = $driverTerm['id'];
		}
		$driverTerm or $this->error('未找到投票活动，或活动已过期。');
		$config = unserialize($driverTerm['config']) and $this->rankConfig = array_merge($this->rankConfig, $config);
		$driverSnap = M("DriverSnap")->where("cid=%d", $this->sid)->order("id desc")->find();
		$this->driverTerm = $driverTerm;
		$this->rank = new \Utuo\Rank( array('namespace' => $this->rankConfig['rank_name']) );
		$this->rankSnap = new \Utuo\Rank( array('namespace' => $this->rankConfig['rank_snap_name']) );
		$driverTerm['config'] = $this->rankConfig;
		$driverTerm['driverSnap'] = $driverSnap;
		$this->assign("termId", $this->termId);
		$this->assign("driverTerm", $driverTerm);
	}
	
	public function indexAction() {
		$this->display("Site/Driver/index");
	}
	
	/**
	 * 参加活动表单
	 */
	public function joinFormAction() {
		C("TOKEN_ON", true);
		$join = D("Driver")->where("open_id='%s' and cid=%d and term_id=%d", $this->open_id, $this->cid, $this->termId)->find();
		$this->assign("join", $join);
		$this->display("Site/Driver/joinForm");
	}
	
	/**
	 * 投票表单
	 */
	public function voteFormAction() {
		C("TOKEN_ON", true);
		$serviceNo =  I("service_no", "");
		$this->assign("serviceNo", $serviceNo);
		$this->display("Site/Driver/voteForm");
	}
	
	/**
	 * 提交参加司机投票活动
	 */
	public function joinAction() {
		C("TOKEN_ON", true);
		$d = D("Driver");
		// $face = $this->getFaceImg() or $this->ajaxError("未上传头像");
		if( $d->create() ) {
			$n = clone $d;
			// $d->face = $face;
			$this->sid or $this->ajaxError("未找到参与活动的网站~");
			$d->open_id or $this->ajaxError("点击图文消息进入,才能参与活动哦~");
			$d->cid = $this->sid;
			$d->term_id = $this->termId;
			$n->where("open_id='%s' and cid=%d and term_id=%d", $this->open_id, $this->cid, $this->termId)->find() and $this->ajaxError("您已参与过活动了,不能重复参与~");
			false != $d->add() and $this->ajaxSuccess("恭喜您已成功报名\"{$this->driverTerm['name']}\"活动。");
		}
		$this->ajaxError($d->getError());
	}
	
	
	/**
	 * 投票表单提交
	 */
	public function voteAction() {
		/*活动时间*/
		$now = time();
		if ( $this->rankConfig['begin_time'] > $now ) {
			$this->ajaxError("投票未开始.");
		} elseif( $now > $this->rankConfig['end_time'] ) {
			$this->ajaxError("投票已结束.");
		}
		C("TOKEN_ON", true);
		$serviceNo = I("service_no", 0 ) or $this->ajaxError("请输入服务号");
		/* 验证司机 */
		$driver = M("Driver")->where(array('service_no'=>$serviceNo, 'cid'=>$this->cid, 'term_id'=> $this->termId, 'is_deleted' => 0))->find();
		if( !$driver ) {
			$this->ajaxError("该车主没有参加\"{$this->driverTerm['name']}\"活动,不能向TA投票。");
		} elseif( $driver['status'] == 0 ) {
			$this->ajaxError("该车主没有成功参加\"{$this->driverTerm['name']}\"活动,不能向TA投票。");
		}
		if ( $driver['open_id'] == $this->open_id) {
			$this->ajaxError("不能给自已投票.");
		}
		/* 验证之前提交  */
		$driverVote = M("DriverVote")->where(array("open_id" => $this->open_id, "cid" => $this->cid, "term_id" => $this->termId))->order("id desc")->find();
		if( $now - $driverVote['create_time']*1 < 1800 ) {
			$min = round((1800-($now - $driverVote['create_time']))/60);
			$this->ajaxError("您刚投过票请".($min<1?1:$min)."分后再来投票." );
		}
		$driverVote = M("DriverVote")->where(array("open_id" => $this->open_id, "cid" => $this->cid, "term_id" => $this->termId, "driver_id" => $driver['id']))->find();
		if ( $driverVote ) {
			$this->ajaxError("不能对该司机重复投票");
		} elseif( false === $driverVote ) {
			$this->ajaxError("网络错误请重试");
		}
		/* 完成投票 */
		$ip = get_client_ip();
		if ( false !== M("DriverVote")->add(array('open_id'=>$this->open_id, 'driver_id'=>$driver['id'], 'create_time'=>time(), 'cid' => $this->cid, 'term_id' => $this->termId, 'ip' => $ip )) ) {
			$this->rank->increase($driver['id']);
			false !== M("Driver")->where('id=%d', $driver['id'])->save(array( // and cid=%d and term_id=%d , $this->cid, $this->termId
				'vote' => array('exp', 'vote+1'), // 避免使用$driver['vote'] + 1
				'last_vote_time' => time(),
			)) and $this->ajaxSuccess("投票成功!");
		}
		$this->ajaxError("投票失败!");
	}
	
	/**
	 * 前200名
	 */
	public function topListAction() {
		$this->display("Site/Driver/topList");
	}
	
	/**
	 * ajax前200名
	 */
	public function getTopListAction() {
		$topList = $this->getTopList();
		$this->process($topList['data']);
		$this->ajaxSuccess('', $topList);
	}
	
	/**
	 * 票数查询页
	 */
	public function voteSearchAction() {
		$driver = M("Driver a")->where("a.open_id='%s' and term_id=%d and cid=%d", $this->open_id, $this->termId, $this->cid)->field("a.*")->find();
		if ( $driver ) {
			$driver['vote'] = $this->rank->getValue($driver['id'])*1;
		}
		$this->process($driver);
		$this->assign("driver", $driver);
		$this->display("Site/Driver/voteSearch");
	}
	
	/**
	 * 票数异步查询
	 */
	public function getVoteAction() {
		$serviceNo = I("service_no", "");
		if ( $serviceNo ) {
			$driver = M("Driver a")->where("a.service_no='%s' and term_id=%d and cid=%d", $serviceNo, $this->termId, $this->cid)->field("a.*")->find();
			if ( $driver ) {
				$driver['vote'] = $this->rank->getValue($driver['id'])*1;
			}
		}
		$this->process($driver);
		$this->ajaxSuccess("", array('driver'=>$driver));
	}
	
	/**
	 * 星号与排名处理
	 */
	private function process( &$data ) {
		if ( !$data ) return;
		function star( $str ) {
			if(mb_strlen($str, 'utf8') >= 8) {
				$startStr = mb_substr($str, 0, 3, 'utf8');
				$endStr = mb_substr($str, mb_strlen($str, 'utf8')-4, 4, 'utf8');
				$middleStr = str_repeat("*", mb_strlen($str, 'utf8') - mb_strlen($startStr, 'utf8') - mb_strlen($endStr, 'utf8'));
				return $startStr.$middleStr.$endStr;
			}
			return $str;
		}
		reset($data);
		$key = key($data);
		if ( is_numeric($key) ) {
			foreach ( $data as $k => &$v ) {
				$v['tel'] and $v['tel'] = star($v['tel']);
				$v['name'] =  mb_substr($v['name'], 0, 1, 'utf8').str_repeat('*', strlen($v['name'])/3-1);
				$rank = $this->rankSnap->getRank($v['id']);
				$v['rank'] = false!==$rank ? $rank+1 : $this->rankConfig['noRandText'];
			}
		} else {
			$data['tel'] and $data['tel'] = star($data['tel']);
			$data['name'] =  mb_substr($data['name'], 0, 1, 'utf8').str_repeat('*', strlen($data['name'])/3-1);
			$rank = $this->rankSnap->getRank($data['id']);
			$data['rank'] = false!==$rank ? $rank+1 : $this->rankConfig['noRandText'];
		}
	}
	
	/**
	 * 最后公布排名榜中前200名搜索
	 * @return multitype:number Ambigous <number, mixed, NULL, unknown> unknown
	 */
	private function getTopList() {
		$p = $this->getPage();
		$pageSize = $this->getPageSize();
		$rankList = $this->rankSnap->getList(true, 0, 199); // 上次更新的排行
		/*前200名id*/
		$ids = array();
		foreach ( $rankList as $v ) {
			$ids[key($v)] = current($v);
		}
		$idstr = join(',', array_keys($ids)) or $idstr = 0;
		/*查询前200名*/
		$topListSql = M("Driver a")->field('a.*')->where("a.id in({$idstr})")->order("field(id,0,{$idstr})")->limit(200)->select(false);
		$m = M()->table($topListSql." a, (select @rowNO := 0) b")->field("a.*,(@rowNO := @rowNo+1) AS rowNo");
		$m = M()->table($m->select(false)." a");
		
		$n = clone $m;
		$querySql = "select count(*) count from ".$n->select(false)." a";
		$querySql = preg_replace('/`(\d+)`/', '$1', $querySql);
		$count = M()->query( $querySql );
		$count = $count[0]['count'];
		
		$querySql = $m->limit($pageSize)->page($p)->select(false);
		$querySql = preg_replace('/`(\d+)`/', '$1', $querySql);
		$topList = M()->query( $querySql );
		/*排名*/
		foreach ($topList as $k => &$v) {
			$v['vote'] = $ids[$v['id']];
			$v['name'] =  mb_substr($v['name'], 0, 1, 'utf8').str_repeat('*', strlen($v['name'])/3-1);
		}
		return array(
				'page' => $p,
				'pageSize' => $pageSize,
				'totalRows' => $count,
				'totalPage' => ceil($count / $pageSize),
				'data' => $topList
		);
	}
	
	/**
	 * 前200名搜索
	 * @return multitype:number Ambigous <number, mixed, NULL, unknown> unknown
	 */
	/*private function getTopList() {
		$p = $this->getPage();
		$pageSize = $this->getPageSize();
		$topListSql = M("Driver a")->field('a.*,a.vote as voteCount')->where('a.vote>0')->order('vote desc,last_vote_time asc')->limit(200)->select(false);
		$m = M()->table($topListSql." a, (select @rowNO := 0) b")->field("a.*,(@rowNO := @rowNo+1) AS rowNo");
		$m = M()->table($m->select(false)." a");
		$n = clone $m;
		$count = $n->count();
		$topList = $m->limit($pageSize)->page($p)->select();
		return array(
			'page' => $p,
			'pageSize' => $pageSize,
			'totalRows' => $count,
			'totalPage' => ceil($count / $pageSize),
			'data' => $topList
		);
	}*/
	
	
	/**
	 * 获得上传头像
	 * @return Ambigous <>
	 */
	private function getFaceImg() {
		$upload = new \Utuo\Upload();
		$info = $upload->uploadOne(array("fieldName" => "face"));
		if ( !$info ) {
			$this->ajaxError($upload->getError());
		} else {
			return $info['url'];
		}
	}
	
}